package com.seven.leetcode.problems;

import java.util.Arrays;

/**
 * 1310. 子数组异或查询
 * https://leetcode-cn.com/problems/xor-queries-of-a-subarray/
 * 级别：Medium
 * <p>
 * 有一个正整数数组 arr，现给你一个对应的查询数组 queries，其中 queries[i] = [Li, Ri]。
 * 对于每个查询 i，请你计算从 Li 到 Ri 的 XOR 值（即 arr[Li] xor arr[Li+1] xor ... xor arr[Ri]）作为本次查询的结果。
 * 并返回一个包含给定查询 queries 所有结果的数组。
 * <p>
 * 示例 1：
 * 输入：arr = [1,3,4,8], queries = [[0,1],[1,2],[0,3],[3,3]]
 * 输出：[2,7,14,8]
 * 解释：
 * 数组中元素的二进制表示形式是：
 * 1 = 0001
 * 3 = 0011
 * 4 = 0100
 * 8 = 1000
 * 查询的 XOR 值为：
 * [0,1] = 1 xor 3 = 2
 * [1,2] = 3 xor 4 = 7
 * [0,3] = 1 xor 3 xor 4 xor 8 = 14
 * [3,3] = 8
 * <p>
 * 示例 2：
 * 输入：arr = [4,8,2,10], queries = [[2,3],[1,3],[0,0],[0,3]]
 * 输出：[8,0,4,4]
 * <p>
 * 提示：
 * 1 <= arr.length <= 3 * 10^4
 * 1 <= arr[i] <= 10^9
 * 1 <= queries.length <= 3 * 10^4
 * queries[i].length == 2
 * 0 <= queries[i][0] <= queries[i][1] < arr.length
 *
 * @author : wenguang
 * @date : 2021/5/12 9:55
 */
public class XorQueriesOfASubarray {

    static int n;
    static int[] c = new int[100009];

    public static void main(String[] args) {
        int[] arr = new int[]{1, 3, 4, 8};
        int[][] queries = new int[][]{{0, 1}, {1, 2}, {0, 3}, {3, 3}};
        System.out.println("in:\narr: " + Arrays.toString(arr) + "\nqueries: " + Arrays.deepToString(queries));
        int[] res = xorQueries(arr, queries);
        System.out.println("out: " + Arrays.toString(res));
    }

    public static int[] xorQueries1(int[] arr, int[][] queries) {
        int len = queries.length;
        int[] res = new int[len];

        int[] query;
        for (int i = 0; i < len; i++) {
            query = queries[i];
            int pre = query[0];
            int last = query[1];
            int num = arr[pre];
            for (int j = pre + 1; j <= last; j++) {
                num ^= arr[j];
            }

            res[i] = num;
        }

        return res;
    }

    static int lowbit(int x) {
        return x & -x;
    }

    static void add(int x, int u) {
        for (int i = x; i <= n; i += lowbit(i)) c[i] ^= u;
    }

    static int query(int x) {
        int ans = 0;
        for (int i = x; i > 0; i -= lowbit(i)) ans ^= c[i];
        return ans;
    }

    static public int[] xorQueries(int[] arr, int[][] qs) {
        n = arr.length;
        int m = qs.length;
        for (int i = 1; i <= n; i++) add(i, arr[i - 1]);
        int[] ans = new int[m];
        for (int i = 0; i < m; i++) {
            int l = qs[i][0] + 1, r = qs[i][1] + 1;
            ans[i] = query(r) ^ query(l - 1);
        }
        return ans;
    }
}
